package com.scm.web.controller.purchase;

import java.util.ArrayList;
import java.util.List;

import com.scm.common.config.ReptilemanagerConfig;
import com.scm.common.config.ServerConfig;
import com.scm.common.core.domain.entity.SysUser;
import com.scm.common.core.page.PageDomain;
import com.scm.common.core.page.TableSupport;
import com.scm.common.exception.ServiceException;
import com.scm.common.utils.StringUtils;
import com.scm.common.utils.file.FileUploadUtils;
import com.scm.common.utils.file.FileUtils;
import com.scm.dto.req.purchase.SaveScmPurchaseReq;
import com.scm.dto.resp.QueryPurchasePageResp;
import com.scm.persist.model.ScmInventoryOut;
import com.scm.persist.model.ScmProduct;
import com.scm.persist.model.ScmPurchaseQuotationDetail;
import com.scm.persist.model.purchase.ScmPurchase;
import com.scm.persist.model.purchase.ScmPurchaseInventoryDetail;
import com.scm.service.IScmProductService;
import com.scm.service.IScmPurchaseService;
import com.scm.web.controller.inventory.vo.ScmInventoryInProductDetailsVO;
import com.scm.web.controller.purchase.vo.ScmPurchaseQuotationDetailVo;
import org.apache.commons.compress.utils.Lists;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.scm.common.annotation.Log;
import com.scm.common.enums.BusinessType;
import com.scm.common.core.controller.BaseController;
import com.scm.common.core.domain.AjaxResult;
import com.scm.common.utils.poi.ExcelUtil;
import com.scm.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 采购Controller
 *
 * @author reptilemanager
 * @date 2024-03-24
 */
@Controller
@RequestMapping("/system/purchase")
public class ScmPurchaseController extends BaseController
{
    private String prefix = "purchase";

    @Autowired
    private IScmPurchaseService scmPurchaseService;

    @Autowired
    private IScmProductService scmProductService;

    @Autowired
    private ServerConfig serverConfig;


    public static SaveScmPurchaseReq toSaveScmPurchaseReq(ScmPurchaseFrom scmPurchaseFrom) {
        if (scmPurchaseFrom == null) {
            return null;
        }

        SaveScmPurchaseReq saveScmPurchaseReq = new SaveScmPurchaseReq();
        ScmPurchase scmPurchase = new ScmPurchase();
        scmPurchase.setId(scmPurchaseFrom.getId());
        scmPurchase.setPurchaseOrderNumber(scmPurchaseFrom.getPurchaseOrderNumber());
        scmPurchase.setPurchaseOrderState(scmPurchaseFrom.getPurchaseOrderState());
        scmPurchase.setPurchasingUnit(scmPurchaseFrom.getPurchasingUnit());
        scmPurchase.setPurchasingPeople(scmPurchaseFrom.getPurchasingPeople());
        scmPurchase.setPurchaseDateStr(scmPurchaseFrom.getPurchaseDateStr());

        List<ScmPurchaseQuotationDetailVo> details = scmPurchaseFrom.getProducts();

        List<ScmPurchaseQuotationDetail> detailList = new ArrayList<>();
        for (ScmPurchaseQuotationDetailVo vo : details) {
            ScmPurchaseQuotationDetail scmInventoryInDetail = toScmPurchaseQuotationDetail(vo);
            detailList.add(scmInventoryInDetail);
        }
        saveScmPurchaseReq.setScmPurchase(scmPurchase);
        saveScmPurchaseReq.setScmPurchaseQuotationDetailList(detailList);

        // Not mapped ScmPurchaseFrom fields:
        // details

        // Not mapped ScmPurchase fields:
        // purchaseOrderApprovalStatus
        // purchaseOrderApprovalRemarks
        // purchaseOrderType
        // purchaseDate
        // deliveryDate
        // deliveryDateStr
        // confirmTime
        // confirmTimeStr
        // amount
        // createTime
        // createUser
        // createUserId
        // updateTime
        // updateUser
        // updateUserId
        return saveScmPurchaseReq;
    }





    /*public static ScmPurchaseInventoryDetail toScmPurchaseInventoryDetail(ScmInventoryInProductDetailsVO scmInventoryInProductDetailsVO) {
        if (scmInventoryInProductDetailsVO == null) {
            return null;
        }
        ScmPurchaseInventoryDetail scmInventoryInDetail = new ScmPurchaseInventoryDetail();
        scmInventoryInDetail.setStashId(scmInventoryInProductDetailsVO.getStashId());
        scmInventoryInDetail.setProductId(scmInventoryInProductDetailsVO.getProductId());
        scmInventoryInDetail.setProductCode(scmInventoryInProductDetailsVO.getProductCode());
        scmInventoryInDetail.setProductName(scmInventoryInProductDetailsVO.getProductName());
        scmInventoryInDetail.setProductUnit(scmInventoryInProductDetailsVO.getProductUnit());
        scmInventoryInDetail.setProductCount(scmInventoryInProductDetailsVO.getProductCount());
        scmInventoryInDetail.setInStashAmount(scmInventoryInProductDetailsVO.getInStashAmount());
        scmInventoryInDetail.setRemark(scmInventoryInProductDetailsVO.getRemark());

        // Not mapped ScmInventoryInDetail fields:
        // id
        // inventoryInId
        // stashName
        // createTime
        // createUser
        // updateTime
        // updateUser
        return scmInventoryInDetail;
    }*/

    public static ScmPurchaseQuotationDetail toScmPurchaseQuotationDetail(ScmPurchaseQuotationDetailVo vo) {
        if (vo == null) {
            return null;
        }
        ScmPurchaseQuotationDetail scmPurchaseQuotationDetail = new ScmPurchaseQuotationDetail();
        scmPurchaseQuotationDetail.setPurchaseId(vo.getPurchaseId());
        scmPurchaseQuotationDetail.setSupplyQuotationId(vo.getSupplyQuotationId());
        scmPurchaseQuotationDetail.setSupplyQuotationCode(vo.getSupplyQuotationCode());
        scmPurchaseQuotationDetail.setScmSupplyQuotationDetailId(vo.getScmSupplyQuotationDetailId());
        scmPurchaseQuotationDetail.setDetailType(vo.getDetailType());
        scmPurchaseQuotationDetail.setProductId(vo.getProductId());
        scmPurchaseQuotationDetail.setProductCode(vo.getProductCode());
        scmPurchaseQuotationDetail.setProductName(vo.getProductName());
        scmPurchaseQuotationDetail.setProductUnit(vo.getProductUnit());
        scmPurchaseQuotationDetail.setProductSpec(vo.getProductSpec());
        scmPurchaseQuotationDetail.setProductCount(vo.getProductCount());
        scmPurchaseQuotationDetail.setPrice(vo.getPrice());
        scmPurchaseQuotationDetail.setRemark(vo.getRemark());
        scmPurchaseQuotationDetail.setTaxRate(vo.getTaxRate());
        scmPurchaseQuotationDetail.setDiscountRate(vo.getDiscountRate());
        scmPurchaseQuotationDetail.setAmt(vo.getAmt());

        // Not mapped ScmPurchaseQuotationDetail fields:
        // id
        // tenantId
        // createTime
        // createUser
        // updateTime
        // updateUser
        return scmPurchaseQuotationDetail;
    }

    @RequiresPermissions("system:purchase:view")
    @GetMapping()
    public String purchase()
    {
        return prefix + "/purchase";
    }

    /**
     * 查询采购列表
     */
    @RequiresPermissions("system:purchase:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(ScmPurchase scmPurchase)
    {
       /* startPage();
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer start = (pageDomain.getPageNum() - 1) * 10;*/
        PageDomain pageDomain = TableSupport.buildPageRequest();

        SysUser sysUser = getSysUser();
        // 金额转换
        //orderPageDo.setAmountStr(AmountUtils.fenToStr(scmOrder.getAmount()));
        QueryPurchasePageResp queryPurchasePageResp = scmPurchaseService.selectScmPurchaseList(scmPurchase, pageDomain,sysUser);
        return toTableDataInfo(queryPurchasePageResp.getTotle(),queryPurchasePageResp.getList());
    }

    /**
     * 导出采购列表
     */
    @RequiresPermissions("system:purchase:export")
    @Log(title = "采购", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(ScmPurchase scmPurchase)
    {
        List<ScmPurchase> list = scmPurchaseService.selectScmPurchaseList(scmPurchase);

        ExcelUtil<ScmPurchase> util = new ExcelUtil<ScmPurchase>(ScmPurchase.class);
        return util.exportExcel(list, "采购数据");
    }

    /**
     * 新增采购
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     *  查询采购单 商品系统
     */
    @PostMapping("/detail/list")
    @ResponseBody
    public TableDataInfo detailList(@RequestParam("id") Long id, ModelMap mmap)
    {
        if(id==null||id==0){
            return getDataTable(Lists.newArrayList());
        }
        List<ScmPurchaseQuotationDetail> scmPurchaseInventoryDetails = scmPurchaseService.selectScmPurchaseInventoryDetailList(id);
        //List<ScmInventoryInDetail> list = scmInventoryInService.selectScmInventoryInDetailListList(id);
        return getDataTable(scmPurchaseInventoryDetails);
    }

    @PostMapping("/detail/listByPids")
    @ResponseBody
    public TableDataInfo detailList(@RequestParam("productCodes") String productCodes, ModelMap mmap)
    {
        SysUser sysUser = getSysUser();

        if(StringUtils.isEmpty(productCodes)){
            return getDataTable(Lists.newArrayList());
        }

        String [] pids = productCodes.split(",");

        List<ScmProduct> scmProducts = Lists.newArrayList();
        StringBuilder sb = new StringBuilder("");
        for (String pid : pids) {
            ScmProduct scmProduct = scmProductService.queryScmProductsByCode(sysUser.getTenantId(),pid);
            if(scmProduct==null){
                sb.append("商品编码为").append(pid).append("的商品未同步到系统，请先同步");
            }else{
                scmProducts.add(scmProduct);
            }
        }
        if(org.apache.commons.lang3.StringUtils.isNotEmpty(sb.toString())){
            throw new ServiceException(sb.toString());
        }

        List<ScmPurchaseQuotationDetail> scmPurchaseInventoryDetails = Lists.newArrayList();
        scmProducts.forEach(scmProduct -> {
            //ScmPurchaseInventoryDetail purchaseInventoryDetail = new ScmPurchaseInventoryDetail();

            ScmPurchaseQuotationDetail purchaseInventoryDetail = new ScmPurchaseQuotationDetail();
            purchaseInventoryDetail.setProductId(scmProduct.getId());
            purchaseInventoryDetail.setProductCode(scmProduct.getProductCode());
            purchaseInventoryDetail.setProductName(scmProduct.getProductName());
            purchaseInventoryDetail.setProductUnit(scmProduct.getProductUnit());

            scmPurchaseInventoryDetails.add(purchaseInventoryDetail);
        });
//        List<ScmPurchaseInventoryDetail> scmPurchaseInventoryDetails = scmPurchaseService.selectScmPurchaseInventoryDetailList(id);
        //List<ScmInventoryInDetail> list = scmInventoryInService.selectScmInventoryInDetailListList(id);
        return getDataTable(scmPurchaseInventoryDetails);
    }

    /**
     * 新增保存采购
     */
    @RequiresPermissions("system:purchase:add")
    @Log(title = "采购", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(ScmPurchaseFrom  from)
    {
        //ScmPurchase scmPurchase
        SysUser sysUser = getSysUser();
        SaveScmPurchaseReq saveScmPurchaseReq = toSaveScmPurchaseReq(from);
        return toAjax(scmPurchaseService.insertScmPurchase(saveScmPurchaseReq,sysUser));
    }





    /**
     * 修改采购
     */
    @RequiresPermissions("system:purchase:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        ScmPurchase scmPurchase = scmPurchaseService.selectScmPurchaseById(id);
        mmap.put("scmPurchase", scmPurchase);
        return prefix + "/edit";
    }

    /**
     * 审批
     */
    @RequiresPermissions("system:purchase:edit")
    @GetMapping("/approval/{id}")
    public String approval(@PathVariable("id") Long id, ModelMap mmap)
    {
        ScmPurchase scmPurchase = scmPurchaseService.selectScmPurchaseById(id);
        mmap.put("scmPurchase", scmPurchase);
        return prefix + "/approval";
    }

    /**
     * 修改保存采购
     */
    @RequiresPermissions("system:purchase:edit")
    @Log(title = "采购", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave( ScmPurchaseFrom  from)
    {
        SysUser sysUser = getSysUser();
        SaveScmPurchaseReq saveScmPurchaseReq = toSaveScmPurchaseReq(from);
        return toAjax(scmPurchaseService.updateScmPurchase(saveScmPurchaseReq,sysUser));
    }

    /**
     * 删除采购
     */
    @RequiresPermissions("system:purchase:remove")
    @Log(title = "采购", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(scmPurchaseService.deleteScmPurchaseByIds(ids));
    }


    @GetMapping("/orderToAdd")
    public String orderToAdd(@RequestParam("productIds") String productIds, ModelMap mmap)
    {
        SysUser sysUser = getSysUser();
        ScmPurchase scmPurchase =new ScmPurchase();


        scmPurchase.setOrderProductIds(productIds);

        mmap.put("scmPurchase", scmPurchase);


        return prefix + "/orderToAdd";

    }



    @GetMapping("/uploadPaymentVoucher/{id}")
    public String uploadPaymentVoucher(@PathVariable("id") Long id,ModelMap mmap){
        mmap.put("id", id);

        return prefix +"/upload_payment_voucher";
    }

    @PostMapping("uploadPaymentVoucher")
    @ResponseBody
    public AjaxResult uploadPaymentVoucherPost(MultipartFile receipt_file, Long id){

        if(id == null){
            // todo 异常
            return AjaxResult.error("系统异常");
        }
        try
        {
            // 上传文件路径
            String filePath = ReptilemanagerConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, receipt_file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", receipt_file.getOriginalFilename());
            SysUser sysUser = getSysUser();
            scmPurchaseService.uploadPaymentVoucherPost(id,sysUser,url);
            //orderManager.uploadCredentials(id,sysUser,url);
            return ajax;
        }
        catch (Exception e)
        {
            logger.error("上传文件异常",e);
            return AjaxResult.error(e.getMessage());
        }
    }
}
